package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.user.UserConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.user.dtos.AuthDto;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2020/9/22 15:18
 **/
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;
    @Override
    public ResponseResult loadListByStatus(AuthDto authDto) {
        if(authDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        authDto.checkParam();
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(authDto.getStatus() != null){
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,authDto.getStatus());
        }
        IPage<ApUserRealname> pageParam = new Page(authDto.getPage(),authDto.getSize());
        IPage<ApUserRealname> page = page(pageParam, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(authDto.getPage(),authDto.getSize(),page.getTotal());
        responseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        responseResult.setData(page.getRecords());
        return responseResult;
    }
    /**
     * @param authDto 审核请求参数
     * @param status 审核状态:
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDto authDto, Short status) {
        // 参数检查
        if(authDto == null || authDto.getId()==null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!checkStatus(status)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 修改apuserrealname 中的审核状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(authDto.getId());
        apUserRealname.setStatus(status);
        if(authDto.getMsg()!=null){
            apUserRealname.setReason(authDto.getMsg());
        }
        updateById(apUserRealname);
        // 认证通过，需要添加自媒体账号 和 作者账号
        if (status.equals(UserConstants.PASS_AUTH)) {
            ResponseResult responseResult = createWmUserAndAuthor(authDto);
            if(responseResult!=null){
                return responseResult;
            }
        }

        // 制造异常
        if(authDto.getId()==5){
            System.out.println(1/0);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 创建自媒体账户
     * @param authDto
     * @return
     */
    private ResponseResult createWmUserAndAuthor(AuthDto authDto) {
        // 查询用户认证信息
        ApUserRealname apUserRealname = getById(authDto.getId());
        // 根据用户认证信息中的userId查询 ApUser用户信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据用户名查询对应自媒体信息是否存在
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        // 如果自媒体账户信息不存在 根据apUser创建自媒体账户
        if(wmUser == null){
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setImage(apUser.getImage());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setStatus(UserConstants.PASS_AUTH.intValue());
            wemediaFeign.save(wmUser);
        }
        // 构建作者信息
        createAuthor(wmUser);
        // 将apuser用户信息的flag状态改为1 为自媒体用户
        apUser.setFlag(1);
        apUserMapper.updateById(apUser);
        return null;
    }
    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = articleFeign.findByUserId(apUserId);
        // 添加作者信息
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setUserId(apUserId);
            apAuthor.setWmUserId(wmUser.getId());
            apAuthor.setType(UserConstants.AUTH_TYPE);
            articleFeign.save(apAuthor);
        }
    }

    /**
     * 检查status是否符合要求
     * false 不符合
     * true  符合
     * @param status
     * @return
     */
    private boolean checkStatus(Short status) {
        if(status ==null || (!status.equals(UserConstants.FAIL_AUTH)&&!status.equals(UserConstants.PASS_AUTH))){
            return false;
        }
        return true;
    }
}
